#!/usr/bin/env python
# -*- coding:utf-8 -*-\
import os
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import scipy.spatial.distance as distance
import numpy as np
import cv2
from sklearn.externals import joblib
from sklearn.preprocessing import normalize
from tensorflow.keras.applications import VGG19
from tensorflow.keras.models import Model


def extract_feature(model, image_list, shape, layer):
    sample_count = len(image_list)
    features_batch = np.zeros(shape=(sample_count, 512))

    for i in range(sample_count):
        image = image_list[i]
        img = cv2.resize(image, (shape[0], shape[1]))  # resize
        img = img/255
        img = img.astype(np.float32)
        img = img.reshape((1, shape[0], shape[1], shape[2]))  # batch_size
        feature_map = model.predict(img)

        feature = feature_map[0, :, :, :]
        feature_vector = np.sum(feature, axis=(0, 1))
        features_batch[i, :] = feature_vector

    return features_batch


def cos_sim(vector_a, vector_b):
    """
    计算两个向量之间的余弦相似度
    :param vector_a: 向量 a
    :param vector_b: 向量 b
    :return: sim
    """
    vector_a = np.mat(vector_a)
    # vector_b = np.mat(vector_b)

    num = np.dot(vector_a, vector_b.T)
    denom = np.linalg.norm(vector_a) * np.linalg.norm(vector_b)
    cos = num / denom
    sim = 0.5 + 0.5 * cos  # 归一化到0-1
    return sim


def image_retrieval(image_list, model, shape, layer, something):
    # 特征提取
    SP_feature_woc = extract_feature(model, image_list, shape=shape, layer=layer)
    test_feature = normalize(SP_feature_woc)

    # PCA降维
    meanVals, pca_s, pca_mat = something
    test_feature_PCA = test_feature - meanVals      # 去均值
    test_feature_PCA = np.dot(test_feature_PCA, pca_mat)  # 特征矩阵
    test_feature_PCA /= np.sqrt(pca_s + 1e-6)           # 除以特征值 白化
    test_feature_PCA = normalize(test_feature_PCA)

    # 相似性度量
    dist = cos_sim(test_feature_PCA[0].reshape(1, 339), test_feature_PCA[1:])
    return dist
